<template>
  <div id="globalSider">
    <a-layout-sider
      width="200"
      v-if="loginUserState.loginUser.id"
      breakpoint="lg"
      collapsed-width="0"
    >
      <a-menu
        v-model:selectedKeys="current"
        mode="inline"
        :items="menuItems"
        @click="doMenuClick"
      ></a-menu>
    </a-layout-sider>
  </div>
</template>
<script lang="ts" setup>
import { computed, h, ref, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import { PictureOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons-vue'
import { useLoginUserState } from '@/stores/useLoginUserState.ts'
import { SPACE_TYPE_ENUM } from '@/constants/space.ts'
import { listMyTeamSpaceUserUsingPost } from '@/api/spaceUserController.ts'

const loginUserState = useLoginUserState()
const current = ref<string[]>([])
// 固定的菜单列
const fixedMenuItems = [
  {
    key: '/',
    icon: () => h(PictureOutlined),
    label: '公共图库',
    title: '公共图库',
  },
  {
    key: '/my_space',
    icon: () => h(UserOutlined),
    label: '我的空间',
    title: '我的空间',
  },
  {
    key: '/add_space?type=' + SPACE_TYPE_ENUM.TEAM,
    icon: () => h(TeamOutlined),
    label: '创建团队',
    title: '创建团队',
  },
]
const teamSpaceList = ref<API.SpaceUserVO[]>([])
// 获取团队空间列表
const fetchTeamSpaceList = async () => {
  const res = await listMyTeamSpaceUserUsingPost()
  teamSpaceList.value = res.data
}
watchEffect(() => {
  if (loginUserState.loginUser.id) {
    fetchTeamSpaceList()
  }
})
const menuItems = computed(() => {
  if (teamSpaceList.value.length < 1) {
    return fixedMenuItems
  }
  const teamSpaceSubMenus = teamSpaceList.value.map((spaceUser) => {
    const space = spaceUser.spaceVO
    return {
      key: '/space/' + spaceUser.spaceId,
      label: space?.spaceName,
    }
  })
  const teamSpaceMenuGruop = {
    type: 'group',
    label: '我的团队',
    key: 'teamSpace',
    children: teamSpaceSubMenus,
  }
  return [...fixedMenuItems, teamSpaceMenuGruop]
})
const router = useRouter()
// 菜单点击事件
const doMenuClick = ({ key }) => {
  router.push(key)
}
// 路由切换后，更新菜单选中状态
router.afterEach((to) => {
  current.value = [to.path]
})
</script>

<style scoped></style>
